package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.QStockWarning;
import com.neusoft.neuiotms.dcam.fixed.model.StockWarning;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedStockWarningRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedStockWarningRepositoryImpl extends AbstractRepository
        implements CustomizedStockWarningRepository {

    @Override
    public Page<StockWarning> search(final Pageable pageable, final Searchable searchable) {
        final QStockWarning qStockWarning = QStockWarning.stockWarning;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<StockWarning> query = this.query().selectFrom(qStockWarning);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QStockWarning qStockWarning = QStockWarning.stockWarning;
        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qStockWarning.name, searchable, "name"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetTypeCode"))) {
            where.and(super.containsStr(qStockWarning.assetTypes.any().code, searchable, "assetTypeCode"));
        }
        final String[] assetTypeIds = searchable.getStrArray("assetTypeIds");
        if ((assetTypeIds != null) && (assetTypeIds.length > 0)) {
            where.and(super.inLongs(qStockWarning.assetTypes.any().id, searchable, "assetTypeIds"));
        }
        final String[] assetTypeCodes = searchable.getStrArray("assetTypeCodes");
        if ((assetTypeCodes != null) && (assetTypeCodes.length > 0)) {
            where.and(super.inStrings(qStockWarning.assetTypes.any().code, searchable, "assetTypeCodes"));
        }
        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return StockWarning.class;
    }

}
